package com.swhysc.information.dao.transformer;

import org.hibernate.transform.AliasedTupleSubsetResultTransformer;

import java.io.BufferedReader;
import java.io.Reader;
import java.sql.Clob;
import java.util.HashMap;

/**
 * @Author zmq
 * @Date 2023/8/30 17:42
 * @Description
 */
public class AliasToMapTransformer extends AliasedTupleSubsetResultTransformer {
    public static final AliasToMapTransformer INSTANCE = new AliasToMapTransformer();

    public AliasToMapTransformer() {
    }

    public Object transformTuple(Object[] tuple, String[] aliases) {
        HashMap result = new HashMap(tuple.length);

        for(int i = 0; i < tuple.length; ++i) {
            String alias = aliases[i];
            if (alias != null) {
                Object val = tuple[i];
                if (val != null && val instanceof Clob) {
                    String target = this.clobToString((Clob)val);
                    result.put(alias.toUpperCase(), target);
                } else {
                    result.put(alias.toUpperCase(), val);
                }
            }
        }

        return result;
    }

    private String clobToString(Clob clob) {
        String reString = "";
        Reader is = null;

        try {
            is = clob.getCharacterStream();
            BufferedReader br = new BufferedReader(is);
            String s = br.readLine();

            StringBuffer sb;
            for(sb = new StringBuffer(); s != null; s = br.readLine()) {
                sb.append(s);
            }

            reString = sb.toString();
        } catch (Exception var7) {
            var7.printStackTrace();
        }

        return reString;
    }

    public boolean isTransformedValueATupleElement(String[] aliases, int tupleLength) {
        return false;
    }

    private Object readResolve() {
        return INSTANCE;
    }
}
